<template>
  <edit-dialog :centerDialogVisible="visible" :show-close="false" :default-button="false" @Cancel="handleCancel" :width="width"
    class="addform">
    <template #header>
      <div style="text-align: left;">
        <span>新建</span>
      </div>
    </template>
    <template #content>
      <div>
        <el-form ref="maintenanceRef" :rules="rules" :model="addForm" label-width="110px" :inline="true">
          <!-- 培训主题 -->
          <el-form-item label="培训主题" prop="trainingTopic">
            <el-input placeholder="请输入培训主题" style="width: 260px" v-model="addForm.trainingTopic"
            show-word-limit></el-input>
          </el-form-item>
          <!-- 单位名称 -->
          <el-form-item label="单位名称" prop="unitName">
            <el-select v-model="addForm.unitName" placeholder="请选择单位名称" style="width: 260px" @change="unitNameChange">
              <el-option v-for="item in props.info" :key="item.id" :label="item.unitName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!-- 单位编号 -->
          <el-form-item label="单位编号" prop="unitNumber">
            <el-input placeholder="请输入单位编号" disabled style="width: 260px" v-model="addForm.unitNumber "
              show-word-limit></el-input>
          </el-form-item>
          <!-- 培训日期 -->
          <el-form-item label="培训日期" prop="trainingDate">
            <el-date-picker
              v-model="addForm.trainingDate"
              type="date"
              style="width: 260px"
              placeholder="培训日期"
              @change="time"
            />
          </el-form-item>
          <!-- 培训场次 -->
          <el-form-item label="培训场次" prop="trainingSession">
            <el-input placeholder="请输入培训场次" style="width: 260px" v-model="addForm.trainingSession"
                      show-word-limit></el-input>
          </el-form-item>
          <!-- 参与人数 -->
          <el-form-item label="参与人数" prop="peopleNumber">
            <el-input placeholder="请输入参与人数" style="width: 260px" v-model="addForm.peopleNumber"
                      show-word-limit></el-input>
          </el-form-item>
          <!-- 培训人员 -->
          <el-form-item label="培训人员" prop="trainingPeople">
            <el-input placeholder="请输入培训人员" style="width: 663px" v-model="addForm.trainingPeople"
                      show-word-limit></el-input>
          </el-form-item>
          <!-- 培训内容 -->
          <el-form-item label="培训内容" prop="trainingContent">
            <el-input placeholder="请输入培训内容" style="width: 663px" v-model="addForm.trainingContent"
                      show-word-limit></el-input>
          </el-form-item>
          <!-- 培训学时 -->
          <el-form-item label="培训学时" prop="trainingPeriod">
            <el-input placeholder="请输入培训学时" style="width: 260px" v-model="addForm.trainingPeriod"
                      show-word-limit></el-input>
          </el-form-item>
          <!-- 培训师 -->
          <el-form-item label="培训师" prop="trainer">
            <el-input placeholder="请输入培训师" style="width: 260px" v-model="addForm.trainer"
                      show-word-limit></el-input>
          </el-form-item>
          <!-- 培训时长 -->
          <el-form-item label="培训时长" prop="trainingDuration">
            <el-input placeholder="请输入培训时长" style="width: 260px" v-model="addForm.trainingDuration"
                      show-word-limit></el-input>
          </el-form-item>
          <!-- 是否进行考核 -->
          <el-form-item label="是否进行考核" prop="isAssess">
            <div class="my-4 flex items-center text-sm">
              <el-radio-group class="ml-4" v-model="addForm.isAssess">
                <el-radio label="1">是</el-radio>
                <el-radio label="2">否</el-radio>
              </el-radio-group>
            </div>
            <!-- multiple -->
          </el-form-item>
          <!-- 培训效果评估 -->
          <el-form-item label="培训效果评估" prop="trainingResult">
            <el-input placeholder="请输入培训效果评估" style="width: 663px" v-model="addForm.trainingResult"
                      show-word-limit></el-input>
          </el-form-item>
          <!-- 有无培训台账 -->
          <el-form-item label="有无培训台账" prop="isRecord">
            <el-select v-model="addForm.isRecord" placeholder="有无培训台账" style="width: 260px">
              <el-option value="1" label="有"></el-option>
              <el-option value="2" label="无"></el-option>
            </el-select>
          </el-form-item>
          <!-- 附件 -->
          <el-form-item label="附件" prop="file">
            <HyUpload :file-list="addForm.files" style="width: 500px" />
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button class="buttonCancel" @click="handleCancel">取消</el-button>
        <el-button type="primary" class="btn-ok" @click="handleAddSave(maintenanceRef)" :loading="loading">保存</el-button>
        <el-button type="primary" class="btn-ok" @click="handleAddSubmit(maintenanceRef)" :loading="loading">提交</el-button>
      </span>
    </template>
  </edit-dialog>
</template>

<script setup lang="ts">
import {ref, reactive, watch, provide, nextTick, onMounted, onBeforeUpdate} from 'vue'
import { getProblem, getdevive, getcompanys, addrepair } from '@/api/requst/management'
import { addSaveTrainingRecords, addSubmitTrainingRecords } from '@/api/secure/trainingRecords'
import editDialog from './editDialog/index.vue'
import { useStore } from 'vuex'
import { ElMessage, dayjs } from 'element-plus'
import { baseUrlConfig } from '@/config/config'
import type { FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus'
import { deleteFile } from '@/api/common'
import store from '@/store'
import HyUpload from "./components/HyUpload.vue";
const tilte = ref('新建')
const loading = ref(false)
const goodsFile = ref<Array<any>>([])
const emit = defineEmits(['cancel'])
const width = ref('900px')
const hideUpload = ref(false)
const testcomRef = ref()
const maintenanceRef = ref()
const filelist = ref<any[]>([])
const baseGeneralPath = baseUrlConfig.businessBaseUrl
const times = ref('D')
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  info: {
    type: Array,
    default: () => [],
  },
})

// 选择单位
const unitNameChange = () => {
  const selectedUnit = props.info.find(item => item.id === addForm.unitName);
  console.log(selectedUnit)
  addForm.unitId = selectedUnit.id;
  addForm.unitName = selectedUnit.unitName;
  addForm.unitNumber = selectedUnit.unitNumber;
  console.log(addForm)
}
//文件上传
const handleExceed: UploadProps['onExceed'] = () => {
  ElMessage.error('上传文件数不能超过1个')
}
/**
 * 取消
 */
const handleCancel = () => {
  //清空绑定值
  addForm.trainingTopic = ''
  addForm.unitId = ''
  addForm.unitName = ''
  addForm.unitNumber = ''
  addForm.trainingDate = ''
  addForm.trainingSession = ''
  addForm.peopleNumber = ''
  addForm.trainingPeople = ''
  addForm.trainingContent = ''
  addForm.trainingPeriod = ''
  addForm.trainer = ''
  addForm.trainingDuration = ''
  addForm.isAssess = ''
  addForm.trainingResult = ''
  addForm.isRecord = ''
  addForm.file = ''
  addForm.files = []
  addForm.createUserId = ''
  filelist.value = []
  emit('cancel')
}

const delFile = (code: string) => {
  deleteFile(code).then(res => {
  })
}

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)
  const code = uploadFile.response?.data?.enclosureCode
  delFile(code)
  hideUpload.value = false
  const values: Array<FileFace> = []
  goodsFile.value.forEach((item, index) => {
    if (item.enclosureCode !== code) {
      values.push(item)
    }
  })
  goodsFile.value = values
}

//上传成功
interface FileFace {
  enclosureContent: string
  enclosureName: string
  enclosureSuffix: string
  resourceAddress: string
  enclosureCode: string
}
const handlerUploadSuccess: UploadProps['onSuccess'] = (resp, uploadFile, uploadFiles) => {
  // console.log(resp, uploadFile, uploadFiles)
  if (resp.code === '1') {
    const item: FileFace = {
      enclosureContent: resp.data.enclosureCode,
      enclosureName: resp.data.enclosureName,
      enclosureSuffix: resp.data.enclosureSuffix,
      resourceAddress: resp.data.resourceAddress,
      enclosureCode: resp.data.enclosureCode
    }
    goodsFile.value.push(item)
    console.log(goodsFile.value);
    // (addForm.file as any[]) = goodsFile.value
    // if (goodsFile.value.length >= 3) {
    //   hideUpload.value = true
    // }
  }
}


const getfiles = (rule: any, value: any, callback: any) => {
  if (!filelist.value.length) {
    callback('请上传附件')
  }
  callback()
}
const rules = ref({});

let addForm = reactive({
  // 培训主题
  trainingTopic: '',
  // 单位id
  unitId: '',
  // 单位名称
  unitName: '',
  // 单位编号
  unitNumber: '',
  // 培训日期
  trainingDate: '',
  // 培训场次
  trainingSession: '',
  // 参与人数
  peopleNumber: '',
  // 培训人员
  trainingPeople: '',
  // 培训内容
  trainingContent: '',
  // 培训学时
  trainingPeriod: '',
  // 培训师
  trainer: '',
  // 培训时长
  trainingDuration: '',
  // 是否进行考核
  isAssess: '',
  // 培训效果评估
  trainingResult: '',
  // 有无培训台账
  isRecord: '',
  // 附件
  file: '',
  files: [],
  // 创建人
  createUserId: ''
})

//弹框点击消失
const cancel = () => {}

const stores = useStore();
//获取登录信息
const createUserId = () => {
  console.log('获取createUserId')
  const login: any = JSON.parse(localStorage.getItem('CacheState'))
  // console.log('login', login.user.userInfo);
  addForm.createUserId = login.user.userInfo.userId
}
//格式化时间
const time = () => {
  addForm.trainingDate = dayjs(addForm.trainingDate).format('YYYY-MM-DD');
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handlePictureCardPreview = (uploadFile: any) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

// 保存
const handleAddSave = async (formEl: any) => {
  rules.value = {
    file: [{ trigger: 'change', message: '请上传附件', required: false,}]
  };
  console.log(addForm)
  if (!formEl) {
    return
  }
  await formEl.validate(async (valid: any) => {
    if (valid) {
      addSaveTrainingRecords(addForm)
        .then(res => {
        if (res.code === '1') {
          //弹框
          ElMessage.success('保存成功')
          //清空绑定值
          addForm.trainingTopic = ''
          addForm.unitId = ''
          addForm.unitName = ''
          addForm.unitNumber = ''
          addForm.trainingDate = ''
          addForm.trainingSession = ''
          addForm.peopleNumber = ''
          addForm.trainingPeople = ''
          addForm.trainingContent = ''
          addForm.trainingPeriod = ''
          addForm.trainer = ''
          addForm.trainingDuration = ''
          addForm.isAssess = ''
          addForm.trainingResult = ''
          addForm.isRecord = ''
          addForm.file = ''
          addForm.files = []
          addForm.createUserId = ''
          filelist.value = []
          // 弹窗消失
          emit('cancel')
        }
      }).catch((err: any) => {
        ElMessage.error(err.message)
      })
    }
  })
}
//提交
const handleAddSubmit = async (formEl: any) => {
  console.log(addForm)
  rules.value = {
    file: [{ trigger: 'change', message: '请上传附件', required: true,}]
  };
  if (!formEl) {
    return
  }
  addForm.file = addForm.files[0].enclosureCode;
  await formEl.validate(async (valid: any) => {
    if (valid) {
      addSubmitTrainingRecords(addForm)
        .then(res => {
          if (res.code === '1') {
            //弹框
            ElMessage.success('提交成功')
            //清空绑定值
            addForm.trainingTopic = ''
            addForm.unitId = ''
            addForm.unitName = ''
            addForm.unitNumber = ''
            addForm.trainingDate = ''
            addForm.trainingSession = ''
            addForm.peopleNumber = ''
            addForm.trainingPeople = ''
            addForm.trainingContent = ''
            addForm.trainingPeriod = ''
            addForm.trainer = ''
            addForm.trainingDuration = ''
            addForm.isAssess = ''
            addForm.trainingResult = ''
            addForm.isRecord = ''
            addForm.file = ''
            addForm.files = []
            addForm.createUserId = ''
            filelist.value = []
            // 弹窗消失
            emit('cancel')
          }
        }).catch((err: any) => {
        ElMessage.error(err.message)
      })
    }
  })
}

onBeforeUpdate(() => {
  createUserId()
  console.log(addForm)
})
</script>


<style scoped>
</style>
